package com.eqdd.yiqidian.ui.gongneng.kehu;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.model.LatLng;
import com.eqdd.annotation.datasave.ToSave;
import com.eqdd.nextinputs.Scheme;
import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.yiqidian.AddKehuActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.AreaBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.utils.MultiChooseBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.map.SelectMapActivity;
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity;
import com.eqdd.yiqidian.ui.select.RichTextResult;
import com.eqdd.yiqidian.ui.select.SelectRichTextActivity;
import com.eqdd.yiqidian.utils.MultiChooseTestUtil;
import com.eqdd.yiqidian.utils.SingleChooseUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.ISelectAble;

public class AddKehuActivity extends SlimBaseMultiEditActivity {
    private AddKehuActivityCustom dataBinding;
    private BottomDialog areaDialog;
    private String result;
    private List<AreaBean> areaBean;
    private ActionSheetDialog clientTypeDialog;
    @ToSave
    RichTextResult richTextResult;
    @ToSave
    int clientType = -1;
    private LocalMedia media;

    @ToSave
    String latAndLong;
    private String quhao;


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_kehu);
        initTopTitleBar(View.VISIBLE, "添加客户");
        initTopRightText("添加", v -> {
            if (!TextUtils.isEmpty(datas.get(0).getContent())) {
                PostRequest<HttpResult> params = OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_CLIENT)
                        .params("owner", user.getGuid())
                        .params("comid", user.getCompanyId())
                        .params("salesTerritoryCode", quhao)
                        .params("cusName", setParam(0))
                        .params("cusType", setParam(1))
                        .params("salesTerritory", setParam(2))
                        .params("address", setParam(3))
                        .params("latAndLong", TextUtils.isEmpty(latAndLong) ? "" : latAndLong)
                        .params("cusCall", setParam(4))
                        .params("url", setParam(5))
                        .params("remark", richTextResult == null ? "" : richTextResult.getContent());
                if (richTextResult != null) {
                    List<LocalMedia> selectMedia = richTextResult.getSelectMedia();
                    for (int i = 0, lenth = selectMedia.size(); i < lenth; i++) {
                        media = selectMedia.get(i);
                        params.params("file" + i, new File(media.isCompressed() ? media.getCompressPath() : media.getPath()));
                    }
                }
                params.execute(new DialogCallBack<HttpResult>(this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            clearData();
                            setResult(Config.SUCCESS);
                            finish();
                        }
                    }
                });
            } else {
                ToastUtil.showLong("请填写客户名称");
            }
        });


    }

    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {
        switch (slimAdapterEx.getData().get(p).getPosition()) {
            case 1:
                if (clientTypeDialog == null) {
                    SingleChooseUtil.getChooseDialog(this, 29,
                            sheetDialog -> {
                                clientTypeDialog = sheetDialog;
                                clientTypeDialog.show();
                            }
                            , (position, strings) -> {
                                clientType = position;
                                datas.get(1).setContent(strings.get(position - 1));
                                slimAdapterEx.notifyItemChanged(1);
                            }

                    );
                } else {
                    clientTypeDialog.show();
                }
                break;
            case 2:
                if (areaDialog == null) {
                    OkGo.<List<AreaBean>>post(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                            .params("type", 0)
                            .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                            .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
                            .execute(new DialogCallBack<List<AreaBean>>(this) {
                                @Override
                                public void onSuccess(Response<List<AreaBean>> response) {
                                    areaBean = response.body();
                                    initAreaPicker();
                                }

                                @Override
                                public void onCacheSuccess(Response<List<AreaBean>> response) {
                                    super.onCacheSuccess(response);
                                    areaBean = response.body();
                                    initAreaPicker();
                                }
                            });
                } else {
                    areaDialog.show();
                }
                break;
            case 3:
                startActivityForResult(SelectMapActivity.class, null, Config.SELECT_MAP);
                break;
            case 6:
                Bundle bundle = new Bundle();
                bundle.putString(Config.TITLE, "备注");
                bundle.putSerializable(Config.RICH_TEXT_RESULT, richTextResult);
                startActivityForResult(SelectRichTextActivity.class, bundle, Config.SELECT_RICH_TEXT);
                break;
        }
    }

    private void initAreaPicker() {
        List<MultiChooseBean> multiChooseBeen = new ArrayList<>();
        multiChooseBeen.addAll(areaBean);
        areaDialog = new MultiChooseTestUtil().getAreaDialog(AddKehuActivity.this, 3, multiChooseBeen, (d, a) -> {
            areaDialog.dismiss();
            result = "";
            for (ISelectAble iSelectAble : a) {
                result += iSelectAble.getName();
            }
            if (((AreaBean) a.get(1).getArg()).getCode().equals("0")) {
                quhao = ((AreaBean) a.get(2).getArg()).getQucode();
            } else {
                quhao = ((AreaBean) a.get(1).getArg()).getCode();
            }
            datas.get(2).setContent(result);
            slimAdapterEx.notifyItemChanged(2);
        });
        areaDialog.show();
    }

    @Override
    protected void setEditBeans() {
        datas.add(new SlimEditEnterBean("客户名称", "", 0, "请输入(必填)"));
        datas.add(new SlimEditEnterBean("客户类型", "", 1, "请选择").setDeal(true));
        datas.add(new SlimEditEnterBean("销售区域", "", 2, "请选择").setDeal(true));
        datas.add(new SlimEditEnterBean("详细地址", "", 3, "请选择").setDeal(true));
        ArrayList<Scheme> schemes = new ArrayList<>();
        schemes.add(StaticScheme.ChineseMobile());
        datas.add(new SlimEditEnterBean("客户电话", "", 4, "请输入").setSchemes(schemes));
        schemes = new ArrayList<>();
        schemes.add(StaticScheme.URL());
        datas.add(new SlimEditEnterBean("网址", "", 5, "请输入").setSchemes(schemes));
        datas.add(new SlimEditEnterBean("备注", "", 6, true, "请输入").setDeal(true));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.SELECT_RICH_TEXT:
                    richTextResult = (RichTextResult) data.getSerializableExtra(Config.RICH_TEXT_RESULT);
                    datas.get(6).setContent("已填写");
                    slimAdapterEx.notifyItemChanged(6);
                    break;
                case Config.SELECT_MAP:
                    LatLng latLng = data.getParcelableExtra(Config.MAP_RESULT_LOCATION);
                    latAndLong = latLng.latitude + "," + latLng.longitude;
                    String map = data.getStringExtra(Config.MAP_RESULT_STRING);
                    datas.get(3).setContent(map);
                    slimAdapterEx.notifyItemChanged(3);
                    break;
            }
        }
    }

}
